<?php

namespace App\Http\Api\Controllers;

use EasyWeChat\Factory;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Pay;

/**
 * 接口Demo
 * @Author MrGuo
 * @Date   2020-08
 */
class DemoController extends Controller {

	/**
	 * 雪花算法唯一数字ID，注意此ID用于接口传输可能造成php或js整数溢出
	 * https://github.com/godruoyi/php-snowflake
	 * @Author MrGuo
	 * @Date   2020-08-06
	 * @return [bigint]   $id
	 */
	function uuid() {
		$snow = new Snowflake();

		return $snow->id();
	}
	/**
	 * 小程序微信支付订单
	 * https://pay.yanda.net.cn/docs/2.x/overview
	 * @Author      MrGuo
	 * @Date        2020-08-06
	 * @param       Request    $request [description]
	 * @return      [type]              [description]
	 */
	public function wxpay(Request $request) {
		$order = [
			'out_trade_no' => $this->uuid(),
			'body' => "小程序支付测试",
			'openid' => "xxxxxx",
			'total_fee' => 1,
		];

		return Pay::wechat(config("pay.wechat"))->miniapp($order);
	}

	/**
	 * 公众号H5支付
	 */
	function wxpay_mp(Request $request) {
		$order = [
			'out_trade_no' => $this->uuid(),
			'body' => "H5支付测试",
			'total_fee' => 1,
		];
		return Pay::wechat(config("pay.wechat"))->wap($order);
	}
	/**
	 * 微信支付回调
	 */
	function wxpay_back(Request $request) {
		$wechat = Pay::wechat(config("pay.wechat"));
		$result = $wechat->verify();
		if (isset($result->out_trade_no)) {
			//根据单号查询并更新数据库
		}
		return $wechat->success();
	}
	/**
	 * 支付宝支付回调
	 */
	function alipay_back(Request $request) {
		$alipay = Pay::alipay(config("pay.alipay"));
		$result = $alipay->verify();
		if (isset($result->out_trade_no)) {
			//根据单号查询并更新数据库
		}
		return $alipay->success();
	}
	/**
	 * 支付宝h5支付
	 * https://pay.yanda.net.cn/docs/2.x/overview
	 */
	function alipay(Request $request) {
		$order = [
			'out_trade_no' => $this->uuid(),
			'total_amount' => 0.01,
			'subject' => "支付测试",
			// 'http_method'  => 'GET' // 如果想在 wap 支付时使用 GET 方式提交，请加上此参数。默认使用 POST 方式提交
		];
		return Pay::alipay(config("pay.alipay"))->wap($order); // laravel 框架中请直接 return
	}
	/**
	 * 公众号授权回调
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function oauth_back(Request $request) {
		$config = config("wechat.official_account.default");

		$app = Factory::officialAccount($config);
		$user = $app->oauth->user();

		// $user 可以用的方法:
		// $user->getId();  // 对应微信的 OPENID
		// $user->getNickname(); // 对应微信的 nickname
		// $user->getAvatar(); // 头像网址
		// $user->getOriginal(); // 原始API返回的结果
		// $user->getToken(); // access_token， 比如用于地址共享时使用

		echo "<h1>openid:{$user->getId()}</h1>";
		echo "<h1>昵称:{$user->getNickname()}</h1>";
		var_dump($user->getOriginal());
	}

	/**
	 * https://www.easywechat.com/docs/4.1/official-account/oauth
	 * 微信公众号授权
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function official_oauth(Request $request) {
		$config = config("wechat.official_account.default");
		$app = Factory::officialAccount($config);

		//静默授权
		/*$response = $app->oauth->scopes(['snsapi_base'])
			->setRequest($request)
			->redirect(request_domain() . "/api/demo/oauth_back");*/
		//用户信息授权
		$response = $app->oauth->scopes(['snsapi_userinfo'])
			->setRequest($request)
			->redirect(request_domain() . "/api/demo/oauth_back");
		return $response;
	}

	/**
	 * https://www.easywechat.com/docs/4.1/basic-services/jssdk
	 * 获取jssdk签名
	 * @param  Request $request [description]
	 * @return [json]           [description]
	 */
	function official_jssdk(Request $request) {
		$config = config("wechat.official_account.default");
		$app = Factory::officialAccount($config);

		$app->jssdk->buildConfig($APIs, false, false, true);
	}

	/**
	 * 公众号模板消息推送
	 * https://www.easywechat.com/docs/4.1/official-account/template_message
	 * @param  Requset $request [description]
	 * @return [type]           [description]
	 */
	function official_push(Request $request) {
		$config = config("wechat.official_account.default");
		$app = Factory::officialAccount($config);

		$res = $app->template_message->send([
			'touser' => 'oUN1NxLNoCzq-B09a0FVYZ1iqLcM',
			'template_id' => 'yz673S53td8r86tVqxsd-LPRzpxbo_lnRCAxM4qIPvs',
			'url' => 'https://easywechat.org',
			'data' => [
				'first' => "恭喜您下单成功！",
				'keyword1' => $this->uuid(),
				'keyword2' => date("Y-m-d H:i"),
				'keyword3' => "100元",
				'remark' => "我们会尽快发货",
			],
		]);
		var_dump($res);
	}

	/**
	 * https://www.easywechat.com/docs/4.1/customize/access_token
	 * 获取公众号access_token
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function access_token(Request $request) {
		$config = config("wechat.official_account.default");
		$app = Factory::officialAccount($config);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
		if (!isset($token['access_token'])) {
			$token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
		}
		var_dump($token['access_token']);
	}

	/**
	 * https://learnku.com/docs/laravel/7.x/validation/7467#rule-accepted
	 * 自定义表单验证
	 * @return [type] [description]
	 */
	function validator(Request $request) {
		$validator = Validator::make($request->all(), [
			'mobile' => 'required|size:11',
			'password' => 'required|min:6|max:20',
		], [], ['mobile' => "手机号"]);
		//var_dump($validator->errors());
		var_dump($validator->errors()->first());
	}

	/**
	 * 微信小程序登录（获取OPENID）
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function miniapp_oauth(Request $request) {
		$config = config("wechat.mini_program.default");
		$app = Factory::miniProgram($config);

		$validator = Validator::make($request->all(), [
			'code' => 'required',
		], [], ['code' => "CODE参数"]);
		if ($validator->errors()->first()) {
			return json_msg(500, $validator->errors()->first());
		}
		try {
			$res = $app->auth->session($request->input("code", ''));
			if (isset($res['openid'])) {
				//session_key建议不要返回给前端
				session("session_key", $res['session_key']);
				return json_msg(0, "微信登录", $res['openid']);
			} else {
				return json_msg(0, "授权登录失败", $res);
			}
		} catch (\Exception $e) {
			//配置错误时排除异常
			return json_msg(500, $e->getMessage());
		}

	}
	/**
	 * 小程序获取二维码
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function miniapp_code(Request $request) {
		$config = config("wechat.mini_program.default");
		$app = Factory::miniProgram($config);

		try {

			$response = $app->app_code->get("pages/index/index?goods_id=1234");
			if (gettype($response) != 'array') {
				//session_key建议不要返回给前端
				if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
					$fname = $this->uuid() . '.png';
					$filename = $response->saveAs(public_path("uploads/qrcodes"), $fname);
					if ($filename) {
						return json_msg(0, "生成二维码成功", "/uploads/qrcodes/" . $fname);
					}
				}
				return json_msg(503, "保存二维码失败", $filename);
			} else {
				return json_msg(501, "生成二维码失败", $response);
			}
		} catch (\Exception $e) {
			//配置错误时排除异常
			return json_msg(500, $e->getMessage());
		}
	}
	/**
	 * 文件上传
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function upload(Request $request) {

	}
}
